package com.sctvcloud.dongqu.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.GroupOrderHelperSingled;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Cache;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.FocusColumn;
import com.sctvcloud.dongqu.beans.HomeListItem;
import com.sctvcloud.dongqu.beans.NewsClickCountBean;
import com.sctvcloud.dongqu.beans.NewsDate;
import com.sctvcloud.dongqu.beans.NewsIdBean;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.NewsListClickRequestBean;
import com.sctvcloud.dongqu.beans.NewsListClickVo;
import com.sctvcloud.dongqu.beans.Titles;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.activities.CommodityDetailActivity;
import com.sctvcloud.dongqu.ui.activities.LoginActivity;
import com.sctvcloud.dongqu.ui.activities.NewesDetailActivity;
import com.sctvcloud.dongqu.ui.activities.TYFOH5Activity;
import com.sctvcloud.dongqu.ui.adapter.CultureTravelAdapter;
import com.sctvcloud.dongqu.ui.adapter.CultureTravelAdapter;
import com.sctvcloud.dongqu.ui.adapter.GreatestAdapter;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.util.NewsDateComparator;
import com.sctvcloud.dongqu.ui.utils.CultureTravelDataAddHelper;
import com.sctvcloud.dongqu.ui.utils.GreatestDataAddHelper;
import com.sctvcloud.dongqu.ui.utils.MutilDateNewsGetHelper;
import com.sctvcloud.dongqu.ui.utils.UIUtils;
import com.sctvcloud.dongqu.utils.ListTypeUtils;
import com.sctvcloud.dongqu.utils.UserManager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 文旅  栏目
 */
public class CultureTravelFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    //    private CultureTravelDataAddHelper dataAddHelper;
    private CultureTravelAdapter adapter;
    private GroupOrderHelperSingled groupOrderHelper;

    private String hour24UrlTemp, bannerUrlTemp;
    private int current24Page = -1, secTitlePos = -1;
    private Date first24TitleDateTemp;

    private int newsFlashType = 0;
    private List<IListShowData> newsList = new ArrayList<>();
    private boolean isReset;
    private String news24Domain = "";
    private Handler handler;

    //    private LittleLifeManager littleLifeManager;

    private long lastGetTime = -1;
    private boolean isFirst = false;
    private boolean isShowLuZhou = false;
    private int newKey = CultureTravelAdapter.VIEWTYPE_NEWS;
    private boolean isRefresh = false;
    private long dyHeight = 0;
    private int newsIndex = 0;
    private int newsPageAll = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_culture_travel, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onLoadMore() {
        if (newsIndex < newsPageAll - 1) {
            if (!getNewsList(CultureTravelAdapter.VIEWTYPE_NEWS, newsIndex + 1)) {
//                dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_NEWS);
                Toast.makeText(getContext(), "获取更多失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        newsList.clear();
        //首次加载数据，或之后下拉刷新
        getChannelList();
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        groupOrderHelper = new GroupOrderHelperSingled();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();

    }

    /**
     * 获取精选模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    resetUrlTemps();
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case CultureTravelAdapter.VIEWTYPE_BANNER:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_EXPRESS:
//                                    expressUrlTemp = fc.getChannelUrl();
//                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_LIVE:
//                                    liveUrlTemp = fc.getChannelUrl();
//                                    break;
                                case CultureTravelAdapter.VIEWTYPE_NEWS:
                                    hour24UrlTemp = fc.getChannelUrl();
                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_POPULAR:
//                                    popularUrlTemp = fc.getChannelUrl();
//                                    break;
                            }
                        }
                    }
//                    if (dataAddHelper == null) {
//                        dataAddHelper = new CultureTravelDataAddHelper();
//                    }
                    lastGetTime = SystemClock.elapsedRealtime();

                    if (!getBannerArray(bannerUrlTemp, CultureTravelAdapter.VIEWTYPE_BANNER)) {
//                        dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_BANNER);
                    }

                }else{
                    refreshLayout.refreshComplete();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.refreshComplete();
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }


        });
    }


    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(newsIndex + 1 < newsPageAll);
    }

    /**
     * 获取 精选-banner数据
     *
     * @param url
     * @param mode
     * @return
     */
    private boolean getBannerArray(String url, final int mode) {
        if (TextUtils.isEmpty(url)) {
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + url + "  mode=" + mode);
            return false;
        }
//        if (!groupOrderHelper.addOne(mode)) {
//            return false;
//        }
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), mode) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(newsItems);
                    hb.setViewType(CultureTravelAdapter.VIEWTYPE_BANNER);
                    newsList.add(hb);
//                    dataAddHelper.setUpDatas(getContext(), hb, CultureTravelAdapter.VIEWTYPE_BANNER);//暂时使用calledIndex来保存mode
                } else {
//                    dataAddHelper.removeUpItem(calledIndex);//暂时使用calledIndex来保存mode
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (!getNewsList(CultureTravelAdapter.VIEWTYPE_NEWS, 0)) {
//                    dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_NEWS);
                }

//                onNetFinish(mode);//暂时使用calledIndex来保存mode
            }
        });
        return true;
    }

    /**
     * 获取 精选--视讯新闻数据
     *
     * @return
     */
    private boolean getNewsList(final int mode, final int index) {
        if (TextUtils.isEmpty(hour24UrlTemp)) {
            return false;
        }
//        if (!groupOrderHelper.addOne(mode)) {
//            return false;
//        }
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), hour24UrlTemp, index, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                newsPageAll = getPageResponse().getData().getPageAll();
                if (ListUtils.isListValued(newsItems)) {
                    newsIndex = index;
                    /***新闻数据请求完成之后获取相应的点击量***/
                    requestNewsClickCount(newsItems);

                } else {
                    if (calledIndex <= 0) {
//                        dataAddHelper.remove24data();
                        current24Page = calledIndex;
                    }
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (newsIndex >= newsPageAll - 1) {
                    refreshLayout.setLoadMoreEnabled(false);
                } else {
                    refreshLayout.setLoadMoreEnabled(true);
                }

            }

            @Override
            public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                return super.doInBackground(newsItems);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
				      onNetFinish();
            }
        });
        return true;
    }

    private List<NewsItem> newsItems;
    /**
     * 获取新闻列表点击量
     *
     * @param list
     */
    private void requestNewsClickCount(List<NewsItem> list) {
        if(ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            newsBean.setId(item.getNewsId());
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) instanceof NewsItem) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (!TextUtils.isEmpty(item.getNewsId())&&countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else {
                                        if (!TextUtils.isEmpty(item.getUrlNewsId())&&countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (isRefresh) {
                            isReset = true;
                            newsList.addAll(newsItems);
//                            dataAddHelper.addOrSet24Datass(getContext(), newsList, true);
                            isRefresh = false;
                        } else {
                            newsList.addAll(newsItems);
//                            dataAddHelper.addOrSet24Datass(getContext(), newsItems, false);
                        }
                        onNetFinish(0);//暂时使用calledIndex来保存mode
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }

    private void resetUrlTemps() {
        bannerUrlTemp = null;
        hour24UrlTemp = null;
        current24Page = -1;
        first24TitleDateTemp = null;
        secTitlePos = -1;
    }

    private synchronized void onNetFinish(int mode) {
//        if (groupOrderHelper.removeOne(mode)) {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
//        }
        if (adapter == null ) {
            adapter =  new CultureTravelAdapter(getContext(), newsList);//dataAddHelper.getAdapter(getContext());
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "精选"));
//            pairs.add(new Pair<>("行为类型", "点击"));
            adapter.setFragment(this);
            adapter.setPairs(pairs);
            recyclerView.setAdapter(adapter);
        }else{
            adapter.setDatass(newsList);
        }
        if (isReset) {
            isReset = false;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    recyclerView.smoothScrollToPosition(0);
////                    recyclerView.scrollTo(0,0);
//                    layoutManager.scrollToPositionWithOffset(0,0);
                }
            }, 700);
        }
    }
}
